package cn.itcast.core.permission.impl;

import java.util.List;

import javax.annotation.Resource;

import cn.itcast.core.permission.PermissionCheck;
import cn.itcast.nsfw.role.entity.Role;
import cn.itcast.nsfw.role.entity.RolePrivilege;
import cn.itcast.nsfw.user.entity.User;
import cn.itcast.nsfw.user.entity.UserRole;
import cn.itcast.nsfw.user.service.UserService;

public class PermissionCheckImpl implements PermissionCheck {
	
	@Resource
	private UserService userService;

	@Override
	public boolean isAccessible(User user, String code) {
		//1、获取的所有权限集合
		List<UserRole> userRolses = user.getUserRoles();
		if (userRolses == null) {
			userRolses = userService.getUserRolesByUserId(user.getId());
		}
		
		//2、将code与权限集合进行比较
		for(UserRole ur: userRolses){
			Role role = ur.getId().getRole();
			for(RolePrivilege rp: role.getRolePrivileges()){
				if(code.equals(rp.getId().getCode())){
					//说明有权限，返回true
					return true;
				}
			}
		}
		return false;
	}

}
